package com.zenithmind.article.service.impl;

import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.baomidou.mybatisplus.core.toolkit.StringUtils;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.zenithmind.article.mapper.ArticleTagMapper;
import com.zenithmind.article.mapper.TagMapper;
import com.zenithmind.article.pojo.domain.Tag;
import com.zenithmind.article.pojo.query.TagQuery;
import com.zenithmind.common.result.PageResult;
import com.zenithmind.article.service.TagService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import java.util.*;
import java.util.stream.Collectors;

@Service
public class TagServiceImpl extends ServiceImpl<TagMapper, Tag> implements TagService {
    
    @Autowired
    private ArticleTagMapper articleTagMapper;
    
    @Override
    public PageResult<Tag> pageTag(TagQuery tagQuery) {
        Page<Tag> page = tagQuery.toPage();
        Page<Tag> tagPage = lambdaQuery().like(StringUtils.isNotBlank(tagQuery.getName()), Tag::getName, tagQuery.getName())
        .page(page);
        return new PageResult<>(tagPage.getRecords(), tagPage.getTotal(), tagPage.getCurrent(), tagPage.getSize());
    }

    @Override
    public Tag addOrUpdateTag(Tag tag) {
        if(StringUtils.isBlank(tag.getId())){
            save(tag);
        }else{
            updateById(tag);
        }
        return tag;
    }
    
    @Override
    public List<Map<String, Object>> getHotTags(Integer limit) {
        // 获取标签使用次数统计
        List<Map<String, Object>> tagUsageStats = articleTagMapper.getTagUsageStats(limit);
        
        if (tagUsageStats.isEmpty()) {
            // 如果没有统计数据，返回普通标签列表
            List<Tag> tags = lambdaQuery()
                    .orderByDesc(Tag::getCreateTime)
                    .last("LIMIT " + limit)
                    .list();
            
            return tags.stream().map(tag -> {
                Map<String, Object> map = new HashMap<>(3);
                map.put("id", tag.getId());
                map.put("name", tag.getName());
                map.put("count", 0);
                return map;
            }).collect(Collectors.toList());
        }
        
        return tagUsageStats;
    }
}
